package com.allen.webservice.jaxrs.config;

import com.allen.webservice.jaxrs.service.StudentService;
import com.allen.webservice.jaxrs.service.impl.StudentServiceImpl;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.jaxrs.json.JacksonJaxbJsonProvider;
import org.apache.cxf.bus.spring.SpringBus;
import org.apache.cxf.endpoint.Server;
import org.apache.cxf.feature.LoggingFeature;
import org.apache.cxf.jaxrs.JAXRSServerFactoryBean;
import org.apache.cxf.transport.servlet.CXFServlet;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.Collections;

@Configuration
@ConditionalOnClass(CXFServlet.class)
public class JaxrsConfig {


    @Resource
    private SpringBus bus;

    @Resource
    private ObjectMapper objectMapper;


    @Bean("StudentServiceImplRs")
    public StudentService studentService() {
        return new StudentServiceImpl();
    }


    /**
     * 服务发布方式
     * ServerFactoryBean进行服务发布
     */
    @Bean
    public Server jaxRsServer() {
        JAXRSServerFactoryBean rsEndpoint = new JAXRSServerFactoryBean();
        rsEndpoint.setBus(bus);
        rsEndpoint.setAddress("/rest/");
        rsEndpoint.setProviders(Arrays.asList(jacksonJaxbJsonProvider()));
        rsEndpoint.setFeatures(Arrays.asList(new LoggingFeature()));
        rsEndpoint.setServiceBeans(Collections.singletonList(new StudentServiceImpl()));
        return rsEndpoint.create();
    }


    /**
     * 配置一个对象与json转换的工具
     */

    @Bean
    public JacksonJaxbJsonProvider jacksonJaxbJsonProvider() {
        return new JacksonJaxbJsonProvider(objectMapper, JacksonJaxbJsonProvider.DEFAULT_ANNOTATIONS);
    }

}
